package com.ruoyi.business.youdaoController.shangyou;


import com.ruoyi.business.services.HttpService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.SaveType;
import com.ruoyi.common.utils.EncrypDES;
import com.ruoyi.common.utils.GetUrlParam;
import com.ruoyi.common.utils.OtherUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.domain.vo.R;
import com.ruoyi.system.protocol.IDynamicSearchService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 百度->小红薯
 */
@RestController
@RequestMapping("ownBdToXHSApi")
public class BDToXHSController {


    @Autowired
    private RedisCache redisCache;

    @Autowired
    private HttpService httpService;
    @Autowired
    private IDynamicSearchService dynamicSearchService;

    private final static String CLASSESEN = "youdao";


  


    /**
     * https://www.ssptqt.com/ownBdToXHSApi/send?channelId=&dmpid=__CLICK_ID__&imeimd5=__IMEI__&idfa=__IDFA__&oaid=__OAID__&oaidmd5=__OAID_MD5__&mac=__MAC__&timestamp=__TS__&os=__OS_TYPE__&ip=__IP__&ua=__UA__&callback_url=__CALLBACK_URL__
     *百度->小红书
     * @param request
     * @return
     * @throws Exception
     */
    @Log(title = "有道", businessType = BusinessType.ESCALATION, esIndex = "youdao_log", saveType = SaveType.ES)
    @RequestMapping("/send")
    public Object send(HttpServletRequest request) throws Exception {
        String queryString = request.getQueryString();
        String channelId = request.getParameter("channelId");
        String dmpid = request.getParameter("dmpid");
        if(StringUtils.isBlank(channelId) || "null".equals(channelId)){
            return R.failure().msg("channelId不能为空");
        }
        if(StringUtils.isBlank(dmpid) || "null".equals(dmpid)){
            return R.failure().msg("dmpid不能为空");
        }

        Map<String, Object> baseParamsMap = GetUrlParam.queryStrToMap(queryString);

        baseParamsMap.remove("channelId");
        baseParamsMap.remove("dmpid");

        Map<String, Object> channelDetail = redisCache.getCacheMapValue(CLASSESEN+"Cache", channelId);
        if(channelDetail == null){
            return R.failure().msg("channelId不正确");
        }
        String url = channelDetail.get("request_address") + "";
        String requestType = channelDetail.get("request_type") + "";
        String requestAddress = GetUrlParam.getRequestAddress(url);
        String staticParameters = GetUrlParam.TruncateUrlPage(url);
        Map<String, Object> staticParamsMap = GetUrlParam.queryStrToMap(staticParameters);
        baseParamsMap.putAll(staticParamsMap);

        String ua = baseParamsMap.get("ua") + "";
        String ip = baseParamsMap.get("ip") + "";
        if(StringUtils.isNotBlank(ua) && !"null".equals(ua)){}else{}
        if(StringUtils.isNotBlank(ip) && !"null".equals(ip)){}else{}



        String callbackUrl = URLDecoder.decode(baseParamsMap.get("callback_url") + "", Constants.UTF8);
        String callbackUrlRequestAddress = GetUrlParam.getRequestAddress(callbackUrl);
        String callbackUrlStaticParameters = GetUrlParam.TruncateUrlPage(callbackUrl);
        if(StringUtils.isNotBlank(callbackUrlStaticParameters)) {
            callbackUrlStaticParameters = callbackUrlStaticParameters.replace("{{ATYPE}}", "__ATYPE__").replace("{{AVALUE}}", "__AVALUE__");
        }

        EncrypDES encrypDES = new EncrypDES();
        String callbackBase = OtherUtils.getServerUrl(request) + "ownBdToXHSApi/callback/"+channelId+"/"+dmpid+"/";
        String encrypt_u = encrypDES.encrypt(callbackUrlRequestAddress);
        String nu = callbackBase + encrypt_u + "?"+callbackUrlStaticParameters;
        baseParamsMap.put("callback_url", URLEncoder.encode(URLEncoder.encode(nu, Constants.UTF8), Constants.UTF8));


        String os = getMapValue(baseParamsMap, "os");
        String idfa = getMapValue(baseParamsMap, "idfa");
        String idfaMd5 = DigestUtils.md5DigestAsHex(idfa.getBytes(Constants.UTF8));


        Map<String, Object> baseParamsMapTemp = new HashMap<>();
        baseParamsMapTemp.put("callback_url", getMapValue(baseParamsMap, "callback_url"));
        baseParamsMapTemp.put("idfa", idfa);
        baseParamsMapTemp.put("idfa_sum", idfaMd5);
        baseParamsMapTemp.put("imei_sum", getMapValue(baseParamsMap, "imeimd5"));
        baseParamsMapTemp.put("mac", getMapValue(baseParamsMap, "mac"));
        baseParamsMapTemp.put("media_name", "baidu");
        baseParamsMapTemp.put("oaid", getMapValue(baseParamsMap, "oaid"));
        baseParamsMapTemp.put("oaid_sum", getMapValue(baseParamsMap, "oaidmd5"));
        baseParamsMapTemp.put("ts_sec",  getMapValue(baseParamsMap, "timestamp"));
        baseParamsMapTemp.put("ip", ip);
        baseParamsMapTemp.put("ua", ua);
        // 一个代理仅提供10个渠道号（N0- N9），渠道号不区分安卓/iOS（同一渠道号可同时投放安卓/iOS (小红书文档中说明的)
        if("1".equals(os)){
            baseParamsMapTemp.put("platform", "IOS");
        }else if("2".equals(os)){
            baseParamsMapTemp.put("platform", "ANDROID");
        }else {
            baseParamsMapTemp.put("platform", "OTHER");
        }

        List<String> tempList = new ArrayList<>();
        for(String key: baseParamsMapTemp.keySet()){
            String value = baseParamsMapTemp.get(key) + "";
            tempList.add(key+"="+value);
        }
        String requestParameters = String.join("&", tempList);

        String uuid = IdUtils.fastSimpleUUID();
        String reqType = "click";
        if("POST".equals(requestType)){
            httpService.sendPost(requestAddress, requestParameters, ip, ua, uuid, reqType);
        }else{
            httpService.sendGet(requestAddress, requestParameters, ip, ua, uuid, reqType);
        }
        return R.success().msg(uuid);
    }


    @Log(title = "有道", businessType = BusinessType.CALLBACK, esIndex = "youdao_log", saveType = SaveType.ES)
    @RequestMapping("/callback/{channelId}/{dmpid}/{encryptedUrl}")
    public Object send(HttpServletRequest request, @PathVariable("channelId") String channelId, @PathVariable("encryptedUrl") String encryptedUrl) throws Exception {
        Map<String, Object> channelDetail = redisCache.getCacheMapValue(CLASSESEN+"Cache", channelId);
        String akey = channelDetail.get("callback_clientid") + "";

        String queryString = request.getQueryString();
        EncrypDES encrypDES = new EncrypDES();
        String requestAddress = encrypDES.decrypt(encryptedUrl);

        //获取请求参数, 并替换属性
        queryString = queryString.replace("__ATYPE__", "activate");
        queryString = queryString.replace("__AVALUE__", "0");
        String sign = DigestUtils.md5DigestAsHex((requestAddress+"?"+queryString+akey).getBytes()).toLowerCase();
        queryString = queryString + "&sign=" + sign;
        String uuid = IdUtils.fastSimpleUUID();
        String reqType = "callback";
        httpService.sendGet(requestAddress, queryString, null, null, uuid, reqType);
        return R.success();
    }




    private String getMapValue(Map<String, Object> map, String key){
        if(map == null){
            return "";
        }
        if(map.get(key) == null){
            return "";
        }
        return map.get(key)+"";
    }

}
